package metrics

import (
	"context"
	"errors"
	"fmt"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"net/http"
)

func Install(ctx context.Context) {
	mux := http.NewServeMux()
	mux.Handle("/metrics", promhttp.Handler())

	server := &http.Server{
		Addr:    "0.0.0.0:9090",
		Handler: mux,
	}

	go func() {
		if err := server.ListenAndServe(); err != nil {
			if errors.Is(err, http.ErrServerClosed) {
				fmt.Printf("prometheus close")
			} else {
				fmt.Printf("error %v", err)
			}
		}
	}()

	go func() {
		<-ctx.Done()
		server.Close()
	}()
}

func NewCounter(opts prometheus.CounterOpts) prometheus.Counter {
	Counter := prometheus.NewCounter(opts)
	prometheus.Register(Counter)
	return Counter
}

func NewCounterVec(opts prometheus.CounterOpts, labelNames []string) *prometheus.CounterVec {
	CounterVec := prometheus.NewCounterVec(opts, labelNames)
	prometheus.Register(CounterVec)
	return CounterVec
}

func NewGauge(opts prometheus.GaugeOpts) prometheus.Gauge {
	Gauge := prometheus.NewGauge(opts)
	prometheus.Register(Gauge)
	return Gauge
}

func NewGaugeVec(opts prometheus.GaugeOpts, labelNames []string) *prometheus.GaugeVec {
	GaugeVec := prometheus.NewGaugeVec(opts, labelNames)
	prometheus.Register(GaugeVec)
	return GaugeVec
}

func NewHistogram(opts prometheus.HistogramOpts) prometheus.Histogram {
	Histogram := prometheus.NewHistogram(opts)
	prometheus.Register(Histogram)
	return Histogram
}

func NewHistogramVec(opts prometheus.HistogramOpts, labelNames []string) *prometheus.HistogramVec {
	HistogramVec := prometheus.NewHistogramVec(opts, labelNames)
	prometheus.Register(HistogramVec)
	return HistogramVec
}
